package modules

import (
	"missevanbot/models"
	"missevanbot/modules/thirdparty"
	"missevanbot/utils"
)

func RunTasks(output chan<- string, room *models.Room) {
	modes := ModeAll(room.ID)
	count := room.TickerCount

	if count >= 5 && taskAnnounce(room.ID, output) {
		// The announcement task will be executed when room open 5 minutes.
		SetStatsTask(room.ID, "announce") // statistics
	}

	if mode := modes[ModePander]; isEnabled(mode) && shouldExec(count, mode) {
		taskPander(output)
		SetStatsTask(room.ID, ModePander) // statistics
	}
	if mode := modes[ModeWater]; isEnabled(mode) && shouldExec(count, mode) {
		taskWater(output)
		SetStatsTask(room.ID, ModeWater) // statistics
	}
}

// taskAnnounce is used to send announcement to particular room,
// then delete the announcement.
func taskAnnounce(rid int64, output chan<- string) bool {
	key := prefixRoom(rid) + "announce" // missevan:[RoomID]:announce
	text := rdb.LPop(ctx, key).Val()
	if text == "" {
		return false
	}
	output <- text
	return true
}

func taskPander(output chan<- string) {
	if text, err := thirdparty.PanderText(); err == nil && text != "" {
		output <- text
	}
}

func taskWater(output chan<- string) {
	c := rdb.SRandMember(ctx, KeyWordWater)
	if text := c.Val(); text != "" {
		output <- text
	}
}

func shouldExec(count int64, dur string) bool {
	d, err := utils.Atoi(dur)
	if err != nil {
		return false
	}
	return count > 0 && count%d == 0
}
